import * as React from 'react';
import type { onSelectType } from './types';
import SuggestItem from './suggestItem';
import './index.module.scss';
const { useState, useEffect, useMemo, memo } = React;

interface SuggestProps {
  searchKey: string;
  onSelect: onSelectType;
}
export default memo(function Suggest(props: SuggestProps) {
  const { searchKey, onSelect } = props;

  const [result, setResult] = useState([]);

  useEffect(() => {
    fetch('/api/rest/search?key=' + encodeURIComponent(searchKey))
      .then((res) => res.json())
      .then((res) => {
        const { result, searchKey: sKey } = res.data;
        if (sKey === searchKey) {
          setResult(result);
        }
      });
  }, [searchKey]);

  const fallBackResult = useMemo(() => {
    if (!result.length) {
      return [
        {
          display: searchKey,
        },
      ];
    }
    return result;
  }, [result, searchKey]);
  return (
    <div styleName="city-suggest">
      <ul styleName="city-suggest-ul">
        {fallBackResult.map((item) => {
          return (
            <SuggestItem
              key={item.display}
              name={item.display}
              onClick={onSelect}
            />
          );
        })}
      </ul>
    </div>
  );
});
